<?php
/**
 * description
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     weiyizheng
 * @date       2022/11/7
 * @time       3:46 下午
 */

namespace Buu\Modules\EsStandard\Controllers;

use App\Admin\Extensions\Tools\UserButton;
use App\Models\EsInstance;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\Log;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Hhz\Drone\Gateway;
use Illuminate\Http\Request;

class EsInstanceController extends AdminController
{
	protected $title = "Es实例";
    private const DEPLOY_CONFIG_File = "DroneConfigMap.json";
    public static array $aDroneConfig = [];


    public function __construct()
    {
        $dir = dirname( __DIR__) . "/Lib/" . self::DEPLOY_CONFIG_File;
        $sConfig = file_get_contents($dir);
        $configMap = json_decode($sConfig, true, 512, JSON_THROW_ON_ERROR);

        self::$aDroneConfig = $configMap['bifrost'];
    }

	public function index(Content $content)
	{
		$content->breadcrumb([
			'text' => $this->title
		]);
		return parent::index($content);
	}

	protected function grid()
	{
		$grid = new Grid(new EsInstance());
        $grid->tools(function (Grid\Tools $tool) {
            $tool->append(new UserButton(UserButton::TYPE_AJAX, 'operate-create', '重载'));
        });
		$grid->paginate(50);
		$grid->disableFilter();
		$grid->disableExport();
		$grid->column('id', 'ID');
		$grid->column('name', '实例名称');
		$grid->column('connect_uri', '连接地址');
		$grid->column('min_conn', '最小连接数');
		$grid->column('max_conn', '最大连接数');
		$grid->actions(function (Grid\Displayers\Actions $actions) {
			$actions->disableDelete();
        });
		return $grid;
	}

	protected function form()
	{
		$form = new Form(new EsInstance());
		$form->footer(function (Form\Footer $footer) {
			$footer->disableEditingCheck();
			$footer->disableCreatingCheck();
			$footer->disableViewCheck();
		});
		$form->tools(function (Form\Tools $tools) {
			$tools->disableDelete();
			$tools->disableView();
		});
		$form->text('name', '实例名称')->placeholder('请输入名称')->setWidth(4, 2)->required();
		$form->text('connect_uri', '连接地址')->setWidth(4, 2)->required();
		$form->number('min_conn', '最小连接数')->setWidth(4, 2)->default('1')->required();
		$form->number('max_conn', '最大连接数')->setWidth(4, 2)->default('20')->required();
		$form->hidden('add_time');
		$form->hidden('update_time');
		$form->hidden('add_username');
		$form->hidden('update_username');
		$form->saving(function (Form $form) {
			if ($form->isCreating()) {
				$form->add_time = time();
				$form->add_username = Admin::user()->username;
			}
			$form->update_time = time();
			$form->update_username = Admin::user()->username;
		});
		return $form;
	}

	// 获取索引
	public function getIndexs(Request $request)
	{
		$instanceId = $request->get('q');
		return EsInstance::getEsIndexs($instanceId);
	}

    public function operateCreate(Request $request)
    {
        try {
            $branch = self::$aDroneConfig['branch'];
            $globalConfig = self::$aDroneConfig['global_config'];
            if (HhzEnv::isProduction()) {
                $globalConfig = $globalConfig['production'];
            } else {
                $globalConfig = $globalConfig['qa'];
            }
            //获取环境变量
            $this->drone($globalConfig['target'], [],
                self::$aDroneConfig['drone_address'],
                $branch);
        } catch (\Exception $e) {
            admin_toastr('操作失败' . $e->getMessage(), 'error', ['timeOut' => 5000]);
            return redirect('/admin/EsStandard/es-instance');
        }
        admin_toastr('操作成功', 'success', ['timeOut' => 5000]);
        return redirect('/admin/EsStandard/es-instance');
    }

    /**
     * 部署无人机
     */
    public function drone(
        string $target,
        array $parameters,
        string $sPromotePath,
        $branch = 'master'
    ) {
        Log::info('部署 :' . $sPromotePath . '--' . $branch . '--' . $target, $parameters);

        $drone = new Gateway(
            'https://drone.haohaozhu.me/api/',
            'nFIBGyqDaNe0N4iS33ir9SAPg54nVAQ3'
        );
        sleep(1);
        return $drone->Promote($sPromotePath, $target, $parameters, $branch);
    }
}